package com.schooleducation.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/regist")
public class RegistController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;

	/**
	 * 获取注册页面
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getRegistPage() {

		return "regist";
	}

	/**
	 * 提交注册信息
	 * @param data
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public String doRegist(String data) {
		User user = (User) JSONObject.toBean(JSONObject.fromObject(data), User.class);
		Map<String, Object> state = new HashMap<String, Object>();
		String userNum = serviceFac.getUserService().doRegist(user);
		if (userNum != null) {
			state.put("regist", "success");
			state.put("userNum", userNum);
			state.put("page", "login");
		} else {
			state.put("regist", "fail");
		}

		return JSONObject.fromObject(state).toString();
	}
	
	/**
	 * 验证昵称是否存在
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "petName", method = RequestMethod.POST)
	@ResponseBody
	public String validatePetName(String data) {
		User user = (User) JSONObject.toBean(JSONObject.fromObject(data), User.class);
		Map<String, Object> state = new HashMap<String, Object>();
		if(serviceFac.getUserService().isRepeatPetName(user)) {
			state.put("repeat", "yes");
		}else{
			state.put("repeat", "no");
		}
		
		return JSONObject.fromObject(state).toString();
	}
}
